import Header from "./components/Header";
import React, {useState,useEffect} from "react";
import {BrowserRouter as Router, Route} from "react-router-dom";
import Task from "./components/Task";
import AddTask from "./components/AddTask";
import Footer from "./components/Footer";
import About from "./components/About";
const App = () => {
  const [showAddTask, setShowAddTask] = useState(false);
  const [tasks,setTask] = useState([])

  useEffect(() => {
    const getTasks = async () => {
      const tasksFromServer = await fetchTasks();
      setTask(tasksFromServer);
    };

    getTasks();

  }, []);

  const fetchTasks = async () => {
    const res = await fetch('http://localhost:5000/tasks');
    const data = await res.json();
    return data;
  };

  const fetchTask = async (id) => {
    const res = await fetch(`http://localhost:5000/tasks/${id}`);
    const data = await res.json();
    return data;
  };

  const showAdd = () => {
    setShowAddTask(!showAddTask);
  };

  const addTask = async (task) => {
    const res = await fetch(`http://localhost:5000/tasks`,{
      method: 'post',
      headers: {
        'Content-type': 'application/json'
      },
      body: JSON.stringify(task)

    })
    //这里我因为不细心少写了个await ,导致页面数据不正常， 控制台说什么没有 单独的 key,不是根本原因
    const data = await res.json();
    setTask([...tasks, data]);



    // const id = Math.floor(Math.random() * 1000) + 1;
    // const newTask = {...task, id}
    // setTask([...tasks, newTask]);

  };

  const deleteTask = async (id) => {
    await fetch(`http://localhost:5000/tasks/${id}`,{
      method: 'delete'
    })
    setTask(tasks.filter((task) => task.id !== id));
  };

  const toggleReminder = async (id) => {
    //这里会发两个请求，因为一个是获取到数据，另外一个请求时修改数据
    const taskToToggle = await fetchTask(id);
    const updTask = {...taskToToggle, reminder: !taskToToggle.reminder};
    const res = await fetch(`http://localhost:5000/tasks/${id}`,{
      method: 'put',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify(updTask)
    });
    const data = await res.json();
    //这里我出现了一个问题，就是在data前面还是打上之前写的！取反，这里不需要再取反了 ，因为上面接口已经帮我们取反了，所以我出现
    //了一个bug就是更新了，刷新db.json还是原来的数据
    setTask(tasks.map((task)=> task.id === id ? {...task, reminder: data.reminder} : task))
  };

  return (
    <Router>
      <div className='container'>
        <Header onAdd={showAdd} showAdd={showAddTask}/>
        <Route path='/' exact render={(props) =>(
          <>
            {showAddTask && <AddTask onAdd={addTask}/>}
            {tasks.length > 0 ? <Task tasks={tasks} onDelete={deleteTask} onToggle={toggleReminder}/> : 'no Task'}
          </>
        )}/>
        <Route path='/about' component={About}/>
        <Footer/>
      </div>
    </Router>

  );

};

export default App;

